import {resolve} from 'path'
import type {ConfigEnv, UserConfig} from 'vite'
import {loadEnv} from 'vite'
import {createVitePlugins} from './build/vite'
import {exclude, include} from "./build/vite/optimize"
// 当前执行node命令时文件夹的地址(工作目录)
const root = process.cwd()

// 路径查找
function pathResolve(dir: string) {
  return resolve(root, '.', dir)
}

// https://vitejs.dev/config/
export default ({command, mode}: ConfigEnv): UserConfig => {
  let env = {} as any
  const isBuild = command === 'build'
  if (!isBuild) {
    env = loadEnv((process.argv[3] === '--mode' ? process.argv[4] : process.argv[3]), root)
  } else {
    env = loadEnv(mode, root)
  }

  // 配置代理规则
  const proxyConfig: Record<string, any> = {
    // 保留原有的API代理（如果需要）
    ['/admin-api']: {
      target: env.VITE_BASE_URL,
      ws: false,
      changeOrigin: true,
      rewrite: (path: string) => path.replace(new RegExp(`^/admin-api`), ''),
    },
    // 添加/token路径的代理配置
    // ['/token']: {
    //   target: env.VITE_BASE_URL,  // 指向后端服务地址
    //   changeOrigin: true,         // 允许跨域
    //   ws: false,                  // 不需要WebSocket支持
    //   // 不需要重写路径，直接转发/token请求
    //   rewrite: (path: string) => path
    // }
  }

  // 添加瓦片代理配置
  if (env.VITE_TILE_PROXY === 'true') {
    proxyConfig['/map-tiles'] = {
      target: env.VITE_TILE_PATH || 'http://localhost:8081', // 本地HTTP服务地址
      changeOrigin: true,
      rewrite: (path: string) => path.replace(/^\/map-tiles/, ''), // 去掉/map-tiles前缀
      configure: (proxy: any) => {
        proxy.on('error', (err: any) => {
          console.log('瓦片代理错误:', err);
        });
        // proxy.on('proxyReq', (proxyReq: any, req: any, res: any) => {
        //   console.log('瓦片请求代理到:', proxyReq.path); // 打印代理后的路径，用于调试
        // });
      }
    };
  }

  return {
    base: env.VITE_BASE_PATH,
    root: root,
    // 服务端渲染
    server: {
      port: env.VITE_PORT, // 端口号
      host: "0.0.0.0",
      open: env.VITE_OPEN === 'true',
      // 启用代理配置
      proxy: proxyConfig
    },
    // 项目使用的vite插件。 单独提取到build/vite/plugin中管理
    plugins: createVitePlugins(),
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@use "@/styles/variables.scss" as *;',
          javascriptEnabled: true,
          silenceDeprecations: ["legacy-js-api"], // 参考自 https://stackoverflow.com/questions/78997907/the-legacy-js-api-is-deprecated-and-will-be-removed-in-dart-sass-2-0-0
        }
      }
    },
    resolve: {
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.scss', '.css'],
      alias: [
        {
          find: 'vue-i18n',
          replacement: 'vue-i18n/dist/vue-i18n.cjs.js'
        },
        {
          find: /\@\//,
          replacement: `${pathResolve('src')}/`
        }
      ]
    },
    build: {
      minify: 'terser',
      outDir: env.VITE_OUT_DIR || 'dist',
      sourcemap: env.VITE_SOURCEMAP === 'true' ? 'inline' : false,
      // brotliSize: false,
      terserOptions: {
        compress: {
          drop_debugger: env.VITE_DROP_DEBUGGER === 'true',
          drop_console: env.VITE_DROP_CONSOLE === 'true'
        }
      },
      rollupOptions: {
        output: {
          manualChunks: {
            echarts: ['echarts'] // 将 echarts 单独打包
          }
        },
      },
    },
    optimizeDeps: {include, exclude}
  }
}
